package com.baizhi.service.impl;

import com.baizhi.dao.VideoDao;
import com.baizhi.dto.UploadVideoDTO;
import com.baizhi.dto.VideoFeedDTO;
import com.baizhi.entity.Video;
import com.baizhi.feign.CategoriesFeign;
import com.baizhi.feign.UserFeign;
import com.baizhi.po.*;
import com.baizhi.service.VideoService;
import com.baizhi.util.AliyunOSSUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 视频(Video)表服务实现类
 *
 * @author makejava
 * @since 2021-09-26 15:34:02
 */
@Service("videoService")
public class VideoServiceImpl extends ServiceImpl<VideoDao, Video> implements VideoService {
    private static final Logger log1 = LoggerFactory.getLogger(VideoServiceImpl.class);
    private String videoName = null;
    //存储地址
    private final static String bucketName = "bzkt-2021-chenjf";

    @Autowired
    private VideoDao videoDao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CategoriesFeign categoriesFeign;
    @Autowired
    private UserFeign userFeign;

    @Override
    public List<Video> queryByPage(Integer page, Integer per_page) {
        Page<Video> page1 = new Page<>(page, per_page);
        Page<Video> videoPage = videoDao.selectPage(page1, null);
        return videoPage.getRecords();
    }

    /**
     * 文件上传到oss
     *
     * @param uploadVideoDTO
     */
    @Override
    public InsertVideoPO insertVideo(UploadVideoDTO uploadVideoDTO, Integer uid) {
        MultipartFile file = uploadVideoDTO.getFile();
        String name = file.getName();
        String contentType = file.getContentType();
        String[] split = contentType.split("/");
        String newName = null;
        if (split[0].equals("image")) {
            //该文件是图片
            newName = split[0] + "/" + System.currentTimeMillis() + "_" + file.getOriginalFilename();

        }
        if (split[0].equals("video")) {
            //该文件是视频
            newName = split[0] + "/" + System.currentTimeMillis() + "_" + file.getOriginalFilename();

        }
        System.out.println("newName = " + newName);
        //文件上传oss
        AliyunOSSUtil.uploadfileBytes(bucketName, newName, file);
        //路径地址前缀
        String path = " https://bzkt-2021-chenjf.oss-cn-hangzhou.aliyuncs.com/";
        //https://bzkt-2021-chenjf.oss-cn-hangzhou.aliyuncs.com/image/1632647645773_%E7%B1%BB%E5%9B%BE.gif

        //创建上传对象
        Video video = new Video();
        video.setTitle(uploadVideoDTO.getTitle());
        video.setIntro(uploadVideoDTO.getIntro());
        video.setUid(uid);
        //图片封面
        String image = path + newName + "?x-oss-process=video/snapshot,t_10000,m_fast";
        System.out.println("image = " + image);
        video.setCover(image);
        video.setLink(path + newName);
        video.setCategoryId(uploadVideoDTO.getCategoryId());
        video.setCreatedAt(new Date());
        video.setUpdatedAt(new Date());

        //视频上传至数据库
        videoDao.insert(video);
        //查询上传视频
        LambdaQueryWrapper<Video> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Video::getId, video.getId());
        Video selectOne = videoDao.selectOne(queryWrapper);
        //创建前端显示数据
        InsertVideoPO insertVideoPO = new InsertVideoPO();
        BeanUtils.copyProperties(selectOne, insertVideoPO);
        //根据分类id获取分类名字
        String categoriesName = null;
        try {
            CategoriesPO categoriesPO = categoriesFeign.queryById(selectOne.getCategoryId());
            categoriesName = categoriesPO.getName();
        } catch (Exception e) {
            categoriesName = "";
        }
        insertVideoPO.setCategory(categoriesName);


        return insertVideoPO;
    }

    @Override
    public List<InsertVideoPO> queryById(Integer uid) {
        LambdaQueryWrapper<Video> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Video::getUid, uid);
        //获取到所有该用户的视频
        List<Video> videos = videoDao.selectList(queryWrapper);
        /**
         * 遍历视频
         * 根据视频的分类id，获取类别名
         */
        List<InsertVideoPO> insertVideoPOS = new ArrayList<>();
        String categoriesName = null;
        InsertVideoPO insertVideoPO = null;
        for (Video video : videos) {
            insertVideoPO = new InsertVideoPO();
            BeanUtils.copyProperties(video, insertVideoPO);
            //根据类别id到对应的类别取出数据
            try {
                CategoriesPO categoriesPO = categoriesFeign.queryById(video.getCategoryId());
                categoriesName = categoriesPO.getName();
            } catch (Exception e) {
                categoriesName = "";
            }
            insertVideoPO.setCategory(categoriesName);

            //喜欢处理
            HashOperations hashOperations = redisTemplate.opsForHash();
            Long size = hashOperations.size("video_like_id:" + video.getId());
            insertVideoPO.setLikes(size.intValue());

            insertVideoPOS.add(insertVideoPO);
        }
        return insertVideoPOS;
    }

    @Override
    public List<QueryVideo> queryByCategoriesId(Integer page, Integer per_page, Integer categoryId) {
        Page<Video> videoPage = new Page<>(page, per_page);
        LambdaQueryWrapper<Video> queryWrapper = new LambdaQueryWrapper<>();
        //标签id等于标签id
        //sql:select * from video where categoryid = #{categoryId} order by create_at desc limit #{page},#{per_page}
        queryWrapper.orderByDesc(Video::getCreatedAt);
        queryWrapper.eq(Video::getCategoryId, categoryId);
        //根据条件获取数据
        Page<Video> selectPage = videoDao.selectPage(videoPage, queryWrapper);
        List<Video> records = selectPage.getRecords();
        //组装前端展示数据
        List<QueryVideo> videos = new ArrayList<>();
        records.forEach(video -> {
            QueryVideo queryVideo = new QueryVideo();
            BeanUtils.copyProperties(video, queryVideo);
            //根据uid，查找对应的up主
            Integer uid = video.getUid();
            String userName = userFeign.queryByUid(uid);
            //根据标签id，查找标签名
            Integer videoCategoryId = video.getCategoryId();
            String name = null;
            try {
                CategoriesPO categoriesPO = categoriesFeign.queryById(videoCategoryId);
                name = categoriesPO.getName();
            } catch (Exception e) {
                name = "";
            }
            queryVideo.setCategory(name);
            // 还没有喜欢,先设置为0
            //喜欢处理
            HashOperations hashOperations = redisTemplate.opsForHash();
            Long size = hashOperations.size("video_like_id:" + video.getId());
            queryVideo.setLikes(size.intValue());

            queryVideo.setUploader(userName);
            videos.add(queryVideo);
        });
        return videos;
    }

    /**
     * 视频详情
     *
     * @param videoId
     * @return
     */
    @Override
    public VideoPO queryByVideoId(Integer videoId) {
        Video video = videoDao.selectById(videoId);
        VideoPO videoPO = new VideoPO();
        BeanUtils.copyProperties(video, videoPO);
        //根据uid获取up博主的对象信息
        OneUserPO oneUserPO = userFeign.queryOneById(video.getUid());
        videoPO.setUploader(oneUserPO);
        //获取类别名
        String name = null;
        try {
            CategoriesPO categoriesPO = categoriesFeign.queryById(video.getCategoryId());
            name = categoriesPO.getName();
        } catch (Exception e) {
            name = "";
        }
        videoPO.setCategory(name);
        /*
            todo: 先将播放次数，点赞次数，是否点赞，是否不喜欢，是否收藏设置为默认，后续处理
         */

        return videoPO;
    }

    @Override
    public FeedVideoPO queryByVideosId(Integer id) {
        LambdaQueryWrapper<Video> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Video::getId, id);
        Video video = videoDao.selectOne(queryWrapper);
        //处理数据
        String categoriesPOName = null;
        try {
            CategoriesPO categoriesPO = categoriesFeign.queryById(video.getCategoryId());
            categoriesPOName = categoriesPO.getName();
        } catch (Exception e) {
            categoriesPOName = "";
        }
        FeedVideoPO feedVideoPO = new FeedVideoPO();
        BeanUtils.copyProperties(video, feedVideoPO);
        feedVideoPO.setCategory(categoriesPOName);
        return feedVideoPO;
    }

    /**
     * 查询视频方法
     */
    @Override
    public VideoFeedDTO queryOneByVideoId(Integer id) {
        LambdaQueryWrapper<Video> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Video::getId, id);
        Video video = videoDao.selectOne(queryWrapper);
        //处理数据
        VideoFeedDTO videoFeedDTO = new VideoFeedDTO();
        videoFeedDTO.setVideoId(id);
        videoFeedDTO.setContent("video");
        videoFeedDTO.setUserId(video.getUid());
        return videoFeedDTO;
    }

    /**
     * 查询所有视频数据
     *
     * @return
     */
    @Override
    public List<VideoES> queryAllVideosForES() {
        List<Video> videos = videoDao.selectList(null);
        //返回数据
        ArrayList<VideoES> videoESArrayList = new ArrayList<>();
        videos.forEach(video -> {
            //数据组装
            VideoES videoES = new VideoES();
            BeanUtils.copyProperties(video, videoES);
            //遍历视频，根据分类id获取分类名
            Integer categoryId = video.getCategoryId();
            CategoriesPO categoriesPO = categoriesFeign.queryById(categoryId);
            String CategoriesName = categoriesPO.getName();
            videoES.setCategory(CategoriesName);
            //redis中获取视频点赞量【喜欢量】
            HashOperations hashOperations = redisTemplate.opsForHash();
            Long size = hashOperations.size("video_like_id:" + video.getId());
            videoES.setLikes(size.intValue());
            //遍历视频，根据用户id获取up名
            Integer userId = video.getUid();
            String userName = userFeign.queryByUid(userId);
            videoES.setUploader(userName);
            videoESArrayList.add(videoES);
        });
        return videoESArrayList;
    }
}

